package com.itheima.reggie.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.itheima.reggie.common.Constant;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mappers.EmployeeMapper;
import com.itheima.reggie.vo.ResultInfo;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void update(Employee emp) {
        emp.setUpdateUser(1L);
        emp.setUpdateTime(new Date());
        employeeMapper.update(emp);
    }

    @Override
    public Employee findById(Long id) {
       return employeeMapper.findById(id);
    }

    @Override
    public List<Employee> findList(String name) {
        return employeeMapper.findList(name);
    }

    //自己补充默认属性，插入新员工
    @Override
    public void add(Employee emp) {

        long id = IdUtil.getSnowflake(1, 1).nextId();
        emp.setId(id);
        String md5Pwd = SecureUtil.md5(Constant.INIT_PASSWORD);
        emp.setPassword(md5Pwd);
        emp.setStatus(Employee.STATUS_ENABLE);
        emp.setCreateTime(new Date());
        emp.setUpdateTime(new Date());
        emp.setCreateUser(1L);
        emp.setUpdateUser(1L);
        employeeMapper.add(emp);
    }

    @Override
    public ResultInfo login(String username, String password) {
       Employee employee= employeeMapper.findByUsername(username);
    if(employee==null)
    {
        return ResultInfo.error("员工不存在");
    }
        String md5Pwd = SecureUtil.md5(password);
       if( !StrUtil.equals(employee.getPassword(), md5Pwd))
       {    return ResultInfo.error("密码不正确");

       }
       if(employee.getStatus()==0)
       {
           return ResultInfo.error("员工被冻结，请联系管理员");
       }
       return ResultInfo.success(employee);
    }
}
